<template>
	<div ref="chartRef" class="w-full h-full"></div>
</template>

<script setup lang="ts" name="pieChart">
import { tryOnUnmounted, useDebounceFn } from '@vueuse/core';
import * as echarts from 'echarts';
import { useEventListener } from '/@/hooks/event/useEventListener';
import { cloneDeep } from 'lodash-es';
const props = defineProps({
	encodeY: {
		type: Number,
		default: 1,
	},
	data: {
		type: Array as any,
		default: () => [],
	},
	name: {
		type: String,
		default: '',
	},
	title: {
		type: String,
		default: '',
	},
	radius: {
		type: String,
		default: '86%',
	},
	center: {
		type: Array<String>,
		default: () => ['50%', '50%'],
	},
});
const chartRef = ref();
let resizeFnPollute = resize;
let removeResizeFn = () => {};
let instance: any;
resizeFnPollute = useDebounceFn(resize, 200);
watch(
	() => props.data,
	(val) => {
		setOptions();
	},
	{
		deep: true,
	}
);
const options = {
	backgroundColor: '#ffffff',
	tooltip: {
		trigger: 'item',
		formatter: '{a} <br/>{b} : {c} ({d}%)',
	},
	toolbox: {
		feature: {
			saveAsImage: {},
		},
	},
	title: {
		text: props.title,
		left: 'center',
	},
	series: [
		{
			name: props.name,
			type: 'pie',
			radius: props.radius,
			center: props.center,
			minAngle: 2,
			data: [],
			label: {
				formatter: '{b}:{c}\n{d}%',
			},
		},
	],
};
const setOptions = () => {
	const seriesData = props.data;
	if (!instance) {
		instance = echarts.init(chartRef.value);
		const { removeEvent } = useEventListener({
			el: window,
			name: 'resize',
			listener: resizeFnPollute,
		});
		removeResizeFn = removeEvent;

		options.series[0].data = seriesData;
		instance.setOption(options);
		return;
	}
	instance.setOption({
		series: [{ data: seriesData }],
	});
};
function resize() {
	const config = {
		animation: {
			duration: 300,
			easing: 'quadraticIn',
		},
	};
	instance.resize(config);
}
onMounted(() => {
	setTimeout(() => {
		setOptions();
	}, 100);
});

tryOnUnmounted(() => {
	removeResizeFn();
});
</script>

<style lang="scss" scoped></style>
